package com.cngphone.AnFetion;

import com.cngphone.AnFetion2.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.cngphone.AnFetion.FetionService.INotifyProgressHandler;
import com.cngphone.AnFetion.FetionService.InitFinishedHandler;

public class FetionLoginActivity extends Activity implements INotifyProgressHandler, InitFinishedHandler {
    CharSequence finishErrorMessage;
    public static final int RESULTCODE_OK = 1;
    public static final int RESULTCODE_FAILED = 2;
    public static final int RESULTCODE_CANCELED = 3;
    public static final int RESULTCODE_EXIT = 4;

    private AutoCompleteTextView txtUsername;
    private EditText txtPassword;
    private Spinner spStatus;
    private boolean loginOk = false;
    private boolean passInput = false;

    private ProgressDialog workingDialog;

    private final OnFocusChangeListener focusListener = new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean focus) {
            if (v == txtUsername && !focus) {
                String s = txtUsername.getText().toString();
                if (s.equals("")) return;
                int index = Settings.getUserIndex(s);
                if (index >= 0) {
                    txtPassword.setText(Settings.passlist[index]);
                    passInput = false;
                    //spStatus.setSelection(Settings.getStatusIndex(Settings.statuslist[index]));
                }
            } else if (v == txtPassword) {
                passInput = true;
            }
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        bindService(MiscUtil.getFetionServiceIntent(this), mConnection, Context.BIND_AUTO_CREATE);

        super.onCreate(savedInstanceState);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onDestroy() {
        if (!loginOk) {
            stopService(MiscUtil.getFetionServiceIntent(this));
        }
        super.onDestroy();
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // System.out.println("key=" + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            releaseAll();
            return true;
        }
        return false;
    }

    private FetionService mBoundService;
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            mBoundService = ((FetionService.LocalBinder) service).getService();

            setContentView(R.layout.login);

            Settings.loadSetting(FetionLoginActivity.this);
            initUserAndPass();

            findViewById(R.id.login).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        if (!passInput) {
                            focusListener.onFocusChange(txtUsername, false);
                        }
                        Settings.loginName = txtUsername.getText().toString();
                        Settings.loginPass = txtPassword.getText().toString();

                        if (Settings.loginName.equals("") || Settings.loginName.equals("")) {
                            AlertDialog dialog = new AlertDialog.Builder(FetionLoginActivity.this).setTitle(
                                    "系统提示").setMessage("请输入手机号和密码！！").setPositiveButton("确定", null).create();
                            dialog.show();
                            return;
                        }

                        Settings.loginStatus = Settings.STATUS_MENU_IDS[spStatus.getSelectedItemPosition()];
                        Settings.remember = ((CheckBox) findViewById(R.id.remember)).isChecked();

                        mBoundService.addNotifyProgress(FetionLoginActivity.this);
                        mBoundService.addInitFinishedHandler(FetionLoginActivity.this);

                        mBoundService.begin();
                    } catch (Exception e) {
                        e.printStackTrace();
                        return;
                    }

                }
            });
            findViewById(R.id.cancel).setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    releaseAll();
                }
            });
            findViewById(R.id.forget).setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String s = txtUsername.getText().toString();
                    if (s.equals("")) return;
                    int index = Settings.getUserIndex(s);
                    if (index >= 0) {
                        deleteUser(index);
                    }
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    private void deleteUser(final int index) {
        AlertDialog dialog = new AlertDialog.Builder(FetionLoginActivity.this).setTitle("系统提示").setMessage(
                "要真的删除此登陆信息么？").setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Settings.removeUser(FetionLoginActivity.this, index);
                Toast.makeText(FetionLoginActivity.this, "成功删除此登陆信息", Toast.LENGTH_SHORT).show();
                initUserAndPass();
            }

        }).setNegativeButton("取消", null).create();
        dialog.show();

    }

    protected void initUserAndPass() {
        txtUsername = ((AutoCompleteTextView) findViewById(R.id.username));
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(FetionLoginActivity.this,
                android.R.layout.simple_dropdown_item_1line, Settings.userlist);
        txtUsername.setAdapter(adapter);
        txtUsername.setText("");
        txtPassword = ((EditText) findViewById(R.id.password));
        txtPassword.setText("");

        spStatus = (Spinner) findViewById(R.id.status);
        ArrayAdapter<CharSequence> spadapter = new ArrayAdapter<CharSequence>(FetionLoginActivity.this,
                android.R.layout.simple_spinner_item, Settings.STATUS_MENU);
        spadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spStatus.setAdapter(spadapter);
        spStatus.setSelection(0);

        if (Settings.loginName != null) {
            txtUsername.setText(Settings.loginName);
            txtPassword.setText(Settings.loginPass);
            spStatus.setSelection(Settings.getStatusIndex(String.valueOf(Settings.loginStatus)));
        } else if (Settings.userlist.length > 0) {
            txtUsername.setText(Settings.userlist[0]);
            txtPassword.setText(Settings.passlist[0]);
            spStatus.setSelection(Settings.getStatusIndex(Settings.statuslist[0]));
        }

        txtUsername.setOnFocusChangeListener(focusListener);
        txtPassword.setOnFocusChangeListener(focusListener);

    }

    @Override
    public void hideNotifyProgress() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
            	if (workingDialog != null)
            		workingDialog.dismiss();
            }
        });
    }

    @Override
    public void showNotifyProgress(final String title, final String text) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                workingDialog = ProgressDialog.show(FetionLoginActivity.this, title, text);
            }
        });
    }

    @Override
    public void initFinished(boolean finishedok, CharSequence errorMessage) {
        if (finishedok) {
            loginOk = true;
            Intent intent = new Intent(FetionLoginActivity.this, FetionListFriends.class);
            startActivity(intent);
            releaseAll();
        } else {
            finishErrorMessage = errorMessage;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mBoundService.removeNotifyProgress(FetionLoginActivity.this);
                    mBoundService.removeInitFinishedHandler(FetionLoginActivity.this);

                    AlertDialog dialog = new AlertDialog.Builder(FetionLoginActivity.this).create();
                    dialog.setTitle("系统提示");
                    dialog.setMessage(finishErrorMessage);
                    dialog.setButton("确定", (DialogInterface.OnClickListener) null);
                    dialog.show();
                }
            });
        }
    }

    private void releaseAll() {
        mBoundService.removeNotifyProgress(FetionLoginActivity.this);
        mBoundService.removeInitFinishedHandler(FetionLoginActivity.this);
        unbindService(mConnection);
        // System.out.println(mBoundService.getReserveNotify());
        finish();
    }
}
